package org.jxy.study.rpc.netty;

import io.netty.channel.Channel;

import java.net.SocketAddress;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import javax.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
 * @author : porteryao
 * @description : 连接管理
 * @date : 2021/3/11 19:18
 */
@Component
public class ConnectManage {

    @Resource
    private NettyClient nettyClient;
    Logger logger = LoggerFactory.getLogger(ConnectManage.class);
    //已建立的通道
    private Map<SocketAddress, Channel> connectedChannel = new ConcurrentHashMap<>();
    //已建立的通道
    private List<Channel> channelList = new CopyOnWriteArrayList<>();
    private void connectServerNode(SocketAddress address) {
        try {
            Channel channel = nettyClient.connect(address);
            addChannel(address, channel);
        } catch (InterruptedException e) {
            e.printStackTrace();
            logger.info("连接服务器失败:{}", address);
        }
    }

    public void addChannel(SocketAddress address, Channel channel) {
        connectedChannel.put(address, channel);
        channelList.add(channel);
    }

    public Channel chooseChannel() {
        if (channelList.isEmpty()) {
            logger.error("无可用连接");
            return null;
        }
        return channelList.get(0);
    }
}
